#include <ctime>
#include <iostream>
#include <boost/asio.hpp>
#include <string>
#include <thread>
#include <functional>

using boost::asio::ip::tcp;
using namespace std;
using namespace boost::asio;

string make_daytime_string()
{
    time_t now = time(0);
    return ctime(&now);
}
class tcp_connection : public enable_shared_from_this<tcp_connection>
{
  public:
    typedef shared_ptr<tcp_connection> pointer;

    static pointer create(io_service &service)
    {
        return pointer(new tcp_connection(service));
    }

    tcp::socket &socket()
    {
        return socket_;
    }

    void start()
    {
        message_ = make_daytime_string();
        async_write(socket_, buffer(message_), bind(&tcp_connection::handle_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
    }

  private:
    tcp_connection(io_service &service) : socket_(service)
    {
    }
    void handle_write(const boost::system::error_code &, size_t)
    {
    }
    tcp::socket socket_;
    std::string message_;
};

class tcp_server
{
  public:
    tcp_server(io_service &service) : acceptor_(service, tcp::endpoint(tcp::v4(), 12345))
    {
        start_accept();
    }

  private:
    void start_accept()
    {
        tcp_connection::pointer new_connection = tcp_connection::create(acceptor_.get_io_service());

        acceptor_.async_accept(new_connection->socket(), bind(&tcp_server::handle_accept, this, new_connection, std::placeholders::_1));
    }
    void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code &error)
    {
        std::cout << "accept connect" << std::endl;
        if (!error)
        {
            new_connection->start();
        }
        start_accept();
    }
    tcp::acceptor acceptor_;
};
int main(int argc, char const *argv[])
{
    try
    {
        io_service service;
        tcp_server server(service);
        service.run();
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }

    return 0;
}
